using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using TK.Common.Tools;

namespace TK.Common.Http
{
    /// <summary>
    /// HttpClient扩展
    /// </summary>
    public static class HttpClientExtensions
    {
        /// <summary>
        /// Sends a POST request as an asynchronous operation to the specified Uri with the given value serialized as JSON.
        /// </summary>
        public static async Task<HttpResponseMessage> PostDataAsync<T>(this HttpClient client, string requestUri, T value)
        {
            var requestContent = new StringContent(JsonSerializer.Serialize(value, ToolHelper.ToJsonOption()), Encoding.UTF8, "application/json");
            return await client.PostAsync(requestUri, requestContent);
        }

        /// <summary>
        /// Sends a POST request as an asynchronous operation to the specified Uri with the given value serialized as JSON.
        /// </summary>
        public static async Task<HttpResponseMessage> PostFormAsync<T>(this HttpClient client, string requestUri, T value)
        {
            var jsonTxt = JsonSerializer.Serialize(value);
            var formData = JsonNode.Parse(jsonTxt).AsObject()
                .Select(m => new KeyValuePair<string, string>(m.Key, m.Value.GetValue<string>()))
                .Where(p => !string.IsNullOrWhiteSpace(p.Value));
            var requestContent = new FormUrlEncodedContent(formData);
            return await client.PostAsync(requestUri, requestContent);
        }
    }
}
